﻿using Lhz.Sc.Entity.Database;
using Lhz.Sc.Entity.Enum;
using System;
using System.Linq;

namespace Lhz.Sc.Business
{
    public static class ServiceQueryableExpansion
    {
        public static IQueryable<Service> QueryByNo(this IQueryable<Service> query, string no)
        {
            if (!string.IsNullOrWhiteSpace(no))
            {
                query = query.Where(r => r.No == no);
            }
            return query;
        }

        public static IQueryable<Service> QueryByApplicationNo(this IQueryable<Service> query, string no)
        {
            if (!string.IsNullOrWhiteSpace(no))
            {
                query = query.Where(r => r.Application.No == no);
            }
            return query;
        }

        public static IQueryable<Service> QueryByApplicationGuid(this IQueryable<Service> query, Guid? applicationGuid)
        {
            if (applicationGuid.HasValue)
            {
                query = query.Where(r => r.ApplicationGuid == applicationGuid.Value);
            }
            return query;
        }

        public static IQueryable<Service> QueryByUserGuid(this IQueryable<Service> query, Guid? userGuid)
        {
            if (userGuid.HasValue)
            {
                var authorizations = new AuthorizationProxy().QueryByUserGuid(userGuid.Value);
                var applicationGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.ApplicationAuthorization).Select(r => r.ObjectGuid);
                var serviceGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.ServiceAuthorization).Select(r => r.ObjectGuid);
                var operationGuids = authorizations.Where(r => r.AuthorizationType == AuthorizationType.OperationAuthorization).Select(r => r.ObjectGuid);
                query = query.Where(r => applicationGuids.Contains(r.ApplicationGuid) || serviceGuids.Contains(r.Guid) || r.Operations.Any(o => operationGuids.Contains(o.Guid)));
            }
            return query;
        }
    }
}
